//
//  THJShareAppVC.m
//  THJXHW
//
//  Created by 河南德艺 on 17/6/6.
//  Copyright © 2017年 河南德艺. All rights reserved.
//

#import "THJShareAppVC.h"
#import "BMChineseSort.h"
#import "Person.h"
//contact
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import <MessageUI/MessageUI.h>

@interface THJShareAppVC ()<MFMessageComposeViewControllerDelegate,UITableViewDelegate,UITableViewDataSource,ABPeoplePickerNavigationControllerDelegate,UIAlertViewDelegate>
{
    NSMutableArray<Person *> *dataArray;
}
//排序后的出现过的拼音首字母数组
@property(nonatomic,strong)NSMutableArray *indexArray;
//排序好的结果数组
@property(nonatomic,strong)NSMutableArray *letterResultArr;
@end

@implementation THJShareAppVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = SingleColor(whiteColor);
    [self getPhoneContact];
    //根据Person对象的 name 属性 按中文 对 Person数组 排序
    self.indexArray = [BMChineseSort IndexWithArray:dataArray Key:@"name"];
    self.letterResultArr = [BMChineseSort sortObjectArray:dataArray Key:@"name"];
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, NavbarHeight, ScreenWidth, ScreenHeight-NavbarHeight)];
    table.tableFooterView = [[UIView alloc] init];
    table.delegate = self;
    table.dataSource = self;
    [self.view addSubview:table];
    
    if(KIsiPhoneX){
        [self setXNavBarWithTitle:@"分享APP"];
    }else{
        [self setNavBarWithTitle:@"分享APP"];
    }
   
}
#pragma mark ---contact----
-(void)getPhoneContact{
    ABAddressBookRef addressBookref = ABAddressBookCreateWithOptions(NULL, NULL);
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBookref, ^(bool granted, CFErrorRef error) {
            CFErrorRef *error1 = NULL;
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
            [self copyAddressBook:addressBook];
        });
    }else if(ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
        CFErrorRef *error1 = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
        [self copyAddressBook:addressBook];
    }else{
        UIAlertView * alert  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有获取通讯录权限,请在设置-隐私-通讯录打开权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        alert.delegate = self;
        [alert show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}
- (void)copyAddressBook:(ABAddressBookRef)addressBook{
    //获取联系人个数
    CFIndex numberOfPeoples = ABAddressBookGetPersonCount(addressBook);
    CFArrayRef peoples = ABAddressBookCopyArrayOfAllPeople(addressBook);
    NSLog(@"有%ld个联系人", numberOfPeoples);
    //循环获取联系人
   dataArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < numberOfPeoples; i++) {
        ABRecordRef person = CFArrayGetValueAtIndex(peoples, i);
        NSString * xing =  (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString * ming =   (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        NSLog(@"LXR3--%@",  (__bridge NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty));
        NSLog(@"LXR4--%@", (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty));
        NSLog(@"LXR5--%@",   (__bridge NSData*)ABPersonCopyImageData(person));
        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        NSString * phoneNo;
        for (int k = 0; k<ABMultiValueGetCount(phone); k++){
            //获取电话Label
            NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * tempstr = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            NSArray *array = [NSArray arrayWithObjects:personPhoneLabel, tempstr, nil];
            phoneNo = array[1];
            NSLog(@"phone--%@",array[1]);
        }
        NSString * name;
        if (!xing) {
            name = ming;
        }else{
            name = [NSString stringWithFormat:@"%@%@",ming,xing];
        }
        Person * p1 = [[Person alloc] init];
        p1.name = name;
        p1.phoneNO = phoneNo;
        [dataArray addObject:p1];
    }
}
#pragma mark ------ UITableView --------
//section的titleHeader
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.indexArray objectAtIndex:section];
}
//section行数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.indexArray count];
}
//每组section个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[self.letterResultArr objectAtIndex:section] count];
}
//section右侧index数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.indexArray;
}
//点击右侧索引表项时调用 索引与section的对应关系
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index;
}
//返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
    }
    //获得对应的Person对象<替换为你自己的model对象>
    Person *p = [[self.letterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    cell.textLabel.text = p.name;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray * nameArr = self.letterResultArr[indexPath.section];
    Person * person = nameArr[indexPath.row];
    NSLog(@"电话---%@---%@",person.name,person.phoneNO);
    NSLog(@"电话---%@",self.indexArray[indexPath.section]);
    [self showMessageView:[NSArray arrayWithObjects:person.phoneNO, nil] title:@"中国铁合金现货网" body:@"我正在使用铁合金现货网APP,找货卖货非常方便，快来试试吧，iOS版下载地址：https://itunes.apple.com/cn/app/%E9%93%81%E5%90%88%E9%87%91%E7%8E%B0%E8%B4%A7%E7%BD%91/id1179909421?mt=8 ，安卓版下载地址：http://sj.qq.com/myapp/detail.htm?apkName=com.hao.thjxhw.net"];
}
#pragma mark ----短信-----
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    switch (result) {
        case MessageComposeResultCancelled:
            NSLog(@"取消发送");
            break;
            
        case MessageComposeResultSent:
            NSLog(@"已发送");
            [self HUDShowMsg:@"已发送" AfterDelayDimiss:2];
            break;
            
        case MessageComposeResultFailed:
            NSLog(@"发送失败");
            break;
            
        default:
            break;
    }
}
- (void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if([MFMessageComposeViewController canSendText]) {
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        // --phones发短信的手机号码的数组，数组中是一个即单发,多个即群发。
        controller.recipients = phones;
        // --短信界面 BarButtonItem (取消按钮) 颜色
        controller.navigationBar.tintColor = [UIColor redColor];
        // --短信内容
        controller.body = body;
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:nil];
    }
    else
    {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                                 message:@"该设备不支持短信功能"
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:alertAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
}
@end
